import pygame
from outman_global import *

class CBall( pygame.sprite.Sprite):

    images = []
    xoffset = 0.0
    yoffset = 0.0
    
    def __init__(self,srcx,srcy,destx,desty,speed):
        pygame.sprite.Sprite.__init__(self,self.containers)
        self.image = self.images[0]
        self.rect = self.image.get_rect()
        self.rect.move_ip(srcx,srcy)
        
        # disintegrate speed into x-direction and y-direction
        length = ((destx-srcx)**2 + (desty-srcy)**2 )**0.5
        self.xspeed = ( speed*abs(destx-srcx) )/length
        self.yspeed = ( speed*abs(desty-srcy) )/length
        if srcx > destx:
            self.xspeed *= -1
        if srcy > desty:
            self.yspeed *= -1

    def update(self):
        # since rect.move_ip not support float arguments, realize rect move in float offset in following method
        # method: accumulate float part offset, when the offset exceed one pixel, add the offset to rect
        self.xoffset += self.xspeed - round(self.xspeed)
        self.yoffset += self.yspeed - round(self.yspeed)
        
        self.rect[0] += round(self.xspeed)
        self.rect[1] += round(self.yspeed)
        if self.xoffset >= 1:
            self.rect[0] += 1
            self.xoffset -= 1
        elif self.xoffset <= -1:
            self.rect[0] -= 1
            self.xoffset += 1

        if self.yoffset >= 1:
            self.rect[1] += 1
            self.xoffset -=1
        elif self.yoffset <= -1:
            self.rect[1] -= 1
            self.yoffset += 1
            
        if not screen_rect.contains(self.rect):
            self.kill()

    def set_speed(self,xspeed,yspeed):
        self.xspeed = xspeed
        self.yspeed = yspeed
